package itsm.isperp.module.controller.constract;

import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.controller.BaseProcessController;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.constant.ConstractConstant;
import itsm.isperp.module.dto.constract.ConstractAcceptance;
import itsm.isperp.module.entity.constract.TmcConstract;
import itsm.isperp.module.response.AaaRes;
import itsm.isperp.module.response.ExcelModel;
import itsm.isperp.module.service.constract.TmcConstractService;
import itsm.isperp.module.utils.ExcelUtils;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
  * @Description 合同管理控制器
  * @Auth ZhiYue
  * @Date 2020/5/17 15:12
*/
@Controller
@RequestMapping("constract/tmc")
public class TmcConstractController extends BaseProcessController<TmcConstract> {

	@Autowired
	protected TmcConstractService tmcConstractService;

	@Override
	public TmcConstractService getService() {
		return this.tmcConstractService;
	}
	
	@Override
	public String getPageTitle() {
		return "TMC合同";
	}

	@RequestMapping("export/excel")
	@ResponseBody
	public Map<String,String> exportExcel(@RequestParam(value="aaa") String ids[],
		  HttpServletRequest request, HttpServletResponse response) throws NoSuchMethodException,
		  IllegalAccessException, InvocationTargetException, IOException {

		Map<String,String> map= new HashMap<>();
		map.put("statusCode","200");
		map.put("message","导出成功！");

		String[] idss = request.getParameterValues("aaa");
		System.out.println(Arrays.toString(idss));

		AaaRes a2 = new AaaRes();
		a2.setId("111");
		a2.setName("人从众");

		AaaRes a1 = new AaaRes();
		a1.setId("111");
		a1.setName("又双叒叕");
		ExcelModel<AaaRes> excelModel = new ExcelModel<>();

		List<String> ths = new ArrayList<String>();
		ths.add("编号");
		ths.add("姓名");

		List<AaaRes> aaaRes = new ArrayList<>();
		aaaRes.add(a1);
		aaaRes.add(a2);
		excelModel.setThs(ths);
		excelModel.setTrs(aaaRes);


		// TODO 调用Excel生成工具类,返回流数据
		Workbook workbook = ExcelUtils.excelStream(excelModel);
		String fileName = "aaa"+System.currentTimeMillis()+".xlsx";
		setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		workbook.write(os);

		os.flush();
		os.close();

		return map;
	}

	@RequestMapping("export/acceptance/report")
	@ResponseBody
	public Map<String, Object> exportAcceptanceReport(HttpServletRequest request,
	  	HttpServletResponse response) throws IOException, InvalidFormatException {

        Map<String, Object> map = new HashMap<>();
        map.put("projectName", "aaaaa");


        String nnn = request.getSession().getServletContext().getRealPath("/");
        String filePath = nnn + "\\fileModel\\aaa.xls";

        System.out.println(filePath);
        FileInputStream is = new FileInputStream(filePath);
        this.setResponseHeader(response, "bbb.xls");
        OutputStream os = response.getOutputStream();
        
        // 加载数据
        XLSTransformer transformer = new XLSTransformer();
        Workbook workbook = transformer.transformXLS(is, map);

        workbook.write(os);

        os.flush();
        os.close();

		return null;
	}

	/**
	 * 批量导出合同报告封面
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @URL localhost:8080/constract/tmc/export/acceptance
	 */
	@RequestMapping("export/acceptance")
	@ResponseBody
	public Map<String, Object> exportAcceptance(HttpServletRequest request, HttpServletResponse response) throws IOException, InvalidFormatException {

		// 1.获取合同验收报告数据
		List<ConstractAcceptance> data = getDate();
		List<String> sheetNames = getSheetNames(data.size());

		// 2.批量填充模板数据
		String nnn = request.getSession().getServletContext().getRealPath("/");
		String filePath = nnn + "fileModel\\ccc.xls";
		FileInputStream is = new FileInputStream(filePath);

		XLSTransformer transformer = new XLSTransformer();
		Workbook workbook = transformer.transformMultipleSheetsList(is, data,
				sheetNames, "aaa", new HashMap(), 0);

		// 3.批量插入条形码
		for (int i = 0; i < data.size(); i++) {
			Sheet sheet = workbook.getSheetAt(i);
			Drawing patriarch = sheet.createDrawingPatriarch();//创建绘图工具对象放循环外可正确显示
			//将图片以字节流的方式输入输出
			String picture = nnn + "fileModel\\aaa.jpg";
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			BufferedImage BufferImg = ImageIO.read(new File(picture));
			ImageIO.write(BufferImg, "JPG", bos);
			HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,0,0,(short) 15, 2,(short)26,5);
			patriarch.createPicture(anchor,workbook.addPicture(bos.toByteArray(), workbook.PICTURE_TYPE_JPEG));

		}
		// 4.响应数据
		setResponseHeader(response, "bbb.xls");
		OutputStream os = response.getOutputStream();
		workbook.write(os);
		os.flush();
		os.close();


		return null;
	}

	@RequestMapping(value = "aaa",method = RequestMethod.GET)
	@ResponseBody
	public ResultMessage aaa() {
		return ResultMessage.newInstance(true, "ok");
	}



	public void setResponseHeader(HttpServletResponse response, String fileName) {
		response.setContentType("application/octet-stream;charset=ISO8859-1");
		response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
		response.addHeader("Pargam", "no-cache");
		response.addHeader("Cache-Control", "no-cache");
	}

	private List<ConstractAcceptance> getDate() {
		List<ConstractAcceptance> data = new ArrayList<>();
		ConstractAcceptance a1 = new ConstractAcceptance();
		a1.setResourceId("1");
		a1.setResourceType("01 验收文档");
		a1.setArrangeDate(new Date());
		a1.setSaveDate(new Date());
		a1.setQzProjectId("123");
		a1.setSystemName("测试项目");
		a1.setBudgetDate("2012.03.01");
		a1.setBudgetId("123");
		a1.setPayDescId("123");
		a1.setPayId("123");
		a1.setResponsible("奇正");
		a1.setCompanyId("ATM8333");
		a1.setTitle("测试项目");
		a1.setPayId("1");
		a1.setTotalPage("1");


		ConstractAcceptance a2 = new ConstractAcceptance();
		a2.setResourceId("1");
		a2.setResourceType("01 验收文档");
		a2.setArrangeDate(new Date());
		a2.setSaveDate(new Date());
		a2.setQzProjectId("123");
		a2.setSystemName("测试项目");
		a2.setBudgetDate("2012.03.01");
		a2.setBudgetId("123");
		a2.setPayDescId("123");
		a2.setPayId("123");
		a2.setResponsible("奇正");
		a2.setCompanyId("ATM8333");
		a2.setTitle("测试项目");
		a2.setPayId("1");
		a2.setTotalPage("1");

		data.add(a1);
		data.add(a2);
		return data;
	}

	private List<String> getSheetNames(int size) {
		List<String> sheetNames = new ArrayList<>();
		for (int i = 0; i < size; i++) {
			sheetNames.add("ATM" + i);
		}
		return sheetNames;
	}


	@Override
	public String getProceessKey() {
		return ConstractConstant.CONSTRACT_PROCESS_KEY;
	}

	@RequestMapping("approveEdit")
	public ModelAndView view(String id, HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		mv.addObject("model", getService().findOne(id));
		return mv;
	}
}
